<?php
class LoginHelper {
	
	public static function isConnected() {
		return !empty($_SESSION['user_connected']);
	}
	
	public static function getUserConnected($fromDB = false) {
		$u = null;
		if (isset($_SESSION['user_connected'])) {
			require_once(CLASS_PATH.'user.class.php');

			$u = new User($_SESSION['user_connected']);
			if ($fromDB) {
				$u->load($u->id_user);
			}
		}
		return $u;
	}
	
	public static function getIdUserConnected() {
		return $_SESSION['user_connected']['id_user'];
	}
	
	public static function connectUser($u) {
		$_SESSION['user_connected'] = array(
			'id_user' => $u->id_user,
			'nom' => $u->nom,
			'prenom' => $u->prenom,
			'email' => $u->email,
			'type_droits_user' => $u->type_droits_user
		);
	}
	
	public static function disconnectUser() {
		unset($_SESSION['user_connected']);
	}
	
	public static function controlAccess($options = array()) {
		$accessGranted = false;
		if (!empty($options['connected'])) {
			$accessGranted = self::isConnected();
		}
		
		if (!empty($options['id_user'])) {
			$id_user_connected = self::getIdUserConnected();
			$accessGranted = ($id_user_connected == $options['id_user']);
		}
		
		if (!empty($options['type_droits_user']) && self::isConnected()) {
			$str = $options['type_droits_user'];
			$u = self::getUserConnected(true);
			
			if (strlen($str) > 2 && substr($str, 0, 2) == ">=") {
				$type_droits_user = intval(substr($str, 2));
				$accessGranted = ($u->type_droits_user >= $type_droits_user);
			}
			else if (strlen($str) > 1 && substr($str, 0, 1) == "=") {
				$type_droits_user = intval(substr($str, 1));
				$accessGranted = ($u->type_droits_user == $type_droits_user);
			}
			else if (strlen($str) > 1 && substr($str, 0, 1) == ">") {
				$type_droits_user = intval(substr($str, 1));				
				$accessGranted = ($u->type_droits_user > $type_droits_user);
			}
			else if (is_numeric($str)) {
				$type_droits_user = intval($str);
				$accessGranted = ($u->type_droits_user == $type_droits_user);
			}
		}
		
		if (!$accessGranted) {
			if (defined('AJAX_RESPONSE') && AJAX_RESPONSE) {
				exit();
			}
			else {
				require_once(HELPER_PATH.'japwordview.helper.php');
				$redirectpage = RACINE_URL;
				if (!empty($options['redirectpage'])) {
					$redirectpage = $options['redirectpage'];
				}
				$v = new JapwordView();
				$v->assign('redirect_page', $redirectpage);
				$v->assign('redirect_timeout', 5);
				$v->display('pages/noaccess.html');
				exit();
			}
		}
	}
}